'use strict';
const jwt = require('jsonwebtoken');

const authenticationList = [
  '/api/info',
];

// app/middleware/error_handler.js
module.exports = () => {
  return async function authentication(ctx, next) {
    const token = ctx.cookies.get('token');
    // try {
    console.log(token);
    if (authenticationList.indexOf(ctx.request.path) !== -1) {
      let user = '';
      try {
        user = jwt.verify(token, 'liuyu000');
      } catch (e) {
        if (token) {
          ctx.throw(401, '用户登录失效');
        } else {
          ctx.throw(401, '用户未登录');
        }
      }

      if (user) {
        ctx.userInfo = user;
        await next();
      } else {
        if (token) {
          ctx.throw(401, '用户登录失效');
        } else {
          ctx.throw(401, '用户未登录');
        }
      }

    } else {
      await next();
    }

  };
};
